<?php

namespace app\backend\controller\role;

use app\backend\model\Role as RoleModel;
use app\backend\services\auth\Permission;
use surface\form\components\Tree;
use surface\helper\FormAbstract;

class Assign extends FormAbstract
{
    private $defaultCheckedKeys = [];

    /**
     * 配置
     *
     * @return array
     */
    public function options(): array
    {
        return [
            'async'    => [
                'url' => '',
            ],
        ];
    }

    private function format(array $lists)
    {
        $data = [];

        foreach ($lists as $k => $v)
        {
            /** @var Permission $v */
            $method = is_array($v->method) ? $v->method : [$v->method];
            $method = implode('|', $method);
            $permission = $method.'.'.$v->route;
            $value = [
                'permission' => $permission,
                'label'    => $v->name . " 【{$permission}】",
                'disabled' => $v->filter !== Permission::ALLOW_AUTHORIZED_FILTER,
            ];
            if ($v->filter !== Permission::ALLOW_AUTHORIZED_FILTER) {
                array_push($this->defaultCheckedKeys, $method.'.'.$v->route);
            }
            if ($children = $v->getChildren())
            {
                $value['children'] = $this->format($v->getChildren());
            }

            array_push($data, $value);
        }

        return $data;
    }

    public function columns(): array
    {
        $id = input('id');
        $model = RoleModel::find($id);
        if (!$model) {
            throw new \Exception('角色不存在');
        }

        $permissions = app('auth')->getPermissions();
        $tree = $this->format($permissions);

        return [
            (new Tree('permissions', RoleModel::$labels['permissions']))->props(
                [
                    'showCheckbox'       => true,
                    'node-key'           => 'permission',
                    'default-expand-all' => true,
                    'check-strictly'     => true,
                    'default-checked-keys' => array_merge($this->defaultCheckedKeys, $model->permissions),
                    'data'               => $tree
                ]
            ),
        ];
    }

    public function save(): bool
    {
        $id = input('id');
        $model = RoleModel::find($id);
        if (!$model) {
            $this->error = '角色不存在';
            return false;
        }
        $permissions = input('permissions');
        $this->format(app('auth')->getPermissions());

        $permissions = array_filter($permissions, function ($v) {
            return !in_array($v, $this->defaultCheckedKeys);
        });

        $model->permissions = array_values($permissions);
        return $model->save();
    }

}
